var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
require("./database/connect"); //引入数据库连接文件
var cors = require("cors");
var { checkToken } = require("./utils/auth-token");
const { createProxyMiddleware } = require("http-proxy-middleware");

// 引入路由模块
var indexRouter = require("./routes/index");
var usersRouter = require("./routes/users");

var app = express();
app.use(cors()); //允许前端跨域访问
app.use(  //node服务代理配置
  "/hehe",
  createProxyMiddleware({
    target: "https://shopapi.smartisan.com",
    pathRewrite:{  //剔除代理路径
      '^/hehe':''
    },
    changeOrigin: true,
  })
);
app.use(logger("dev"));
// body-parser中间件配置
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use(cookieParser());

// 静态资源托管
app.use(express.static(path.join(__dirname, "public")));
// 当用户访问 / 的时候，引导用户从public文件夹找资源

app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use(
  "/client",
  (req, res, next) => {
    // console.log('中间件函数',req.headers);
    checkToken(req, res, next); //验证token的函数
  },
  require("./routes/client.js")
);

module.exports = app;
